import { feedApi } from '/api/feed'
import { topicApi } from '/api/topic'
import { userApi } from '/api/user'
import { checkAuth } from '/store/actions'
import { getServer, isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event, $storage, $utils } from '/utils'

Page({
  data: {
    navList: [] as any,
    navigationHeight: 0,
    list: [] as any,
    activitylist: [] as any,
    access: GlobalData.access,
    // 推荐分类
    categories: [] as DomoFeedCategory[],
    // 当前分类
    category: '' as any,
    noMore: false,
    // 默认是热门标签
    currentIndex: 1,
    // 筛选条件
    query: {
      only_video: false,
      category: 0 as number,
      limit: 15,
    },
    method: 'hot',
    loading: false,
    //广告列表
    advertisingList: [] as any,
    scrollClass: false,
    city: '',
    navData: [] as DomoFeedCategory[],
    navbarList: {
      data: [] as any,
    },
    /** 管理员 */
    admin: false,
    emit: false,
    dataList: [] as any,
  },

  async onLoad(options?: any) {
    if (options.code) {
      wx.setStorage({ key: 'invite', data: options.code })
    }
    if (options.scene) {
      wx.setStorage({ key: 'invite', data: decodeURIComponent(options.scene) })
    }
    this.fetchCategiries()
    this.getMatchList()
    if (isLogin()) {
      // 如果登录了的话，直接触发获取登录信息
      const loginReward = await userApi.getLoginReward()
      if (loginReward.amount) {
        $event.emit('showMessage', {
          message: '每日登录',
          amount: loginReward.amount,
        } as GetRewardMessageReturns)
      }
    }
    $event.on('after:abilities', this, () => {
      // this.isAdmin()
    })
    $event.on('after:boot', this, () => {
      this.setData({ emit: true })
      this.getPosition()
    })
    $event.on('after:login', this, () => {
      const user = wx.getStorageSync(`${getServer()}/logged`).data
      const code = wx.getStorageSync('invite') || 0
      /** 之前可能会涉及到设置错误的邀请码,所以这里判断了''和undefined */
      !user.inviter && code && code != '' && code != user.invite_code
        ? userApi.setInvitee({ invite_code: code })
        : ''
    })
    this.getPosition()
    this.getList()
    $event.on('feed:hideTabbar', this, () => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          hide: true,
        })
      }
    })
    $event.on('feed:showTabbar', this, () => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          hide: false,
        })
      }
    })
    $event.on('message:showMessageDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMeesageDot: isShow,
        })
      }
    })
    $event.on('message:showMineDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMineDot: isShow,
        })
      }
    })
  },
  onShow() {
    // 自定义tab
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
        hide: false,
      })
    }
    // this.getNavbarList()
    this.setData({
      emit: false,
    })
    $event.on('after:changeFeedList', this, (feedId: number) => {
      /** 删除动态列表中的删除项 */
      this.onPullDownRefresh()
    })
    $event.on('after:publishdynamic', this, () => {
      // 发布成功后跳转到关注列表并刷新
      this.setData({
        currentIndex: 1,
      })
      this.updateCurrentTable(1)
    })
    this.getcity()
    // 新规小程序禁止进入首页弹登录窗容易被驳回
    // if (!isLogin()) {
    //   await checkAuth()
    // }
    $event.on(
      'delete:category',
      this,
      ({ feedId, categoryIds }: { feedId: number; categoryIds: number[] }) => {
        console.log(feedId, categoryIds)
        this.data.navData.forEach((item, idx) => {
          categoryIds.forEach((cateId) => {
            if (item.id === cateId) {
              this.data.list[idx].data.forEach((element: any) => {
                if (feedId === element.id) {
                  const data = this.data.list[idx].data.indexOf(element)
                  this.data.list[idx].data.splice(data, 1)
                }
              })
            }
          })
        })
      },
    )
  },
  //跳转更多
  jumpToMore() {
    wx.navigateTo({
      url: '/pages/moreApp/moreApp',
    })
  },
  gocity() {
    // wx.navigateTo({
    //   url: '/pages/report/report',
    // })
  },
  goTeamList(event: any) {
    // let type = event.currentTarget.dataset.type
    // console.log(type)
    // wx.switchTab({
    //   url: '/pages/match/team/team',
    // })
  },
  goEventList(event: any) {
    // wx.navigateTo({
    //   url: '/pages/match/list0/list0',
    // })
  },
  // 获取导航栏列表
  async getNavbarList() {
    this.data.navList = []
    this.data.dataList = []
    const navbarList = await feedApi.getNavbarList()
    this.data.dataList = navbarList.data
    for (let i = 0; i < navbarList.data.length; i++) {
      if (i < 14) {
        this.data.navList.push(navbarList.data[i])
      }
    }
    this.setData({
      navList: this.data.navList,
      dataList: this.data.dataList,
    })
  },
  /** 判断是否为管理员,以显示全部列表 */
  isAdmin() {
    const abilities: any = GlobalData.userAbilities
    abilities &&
      abilities.some((i: any) => {
        return i.name === '[feed] Push To Category'
      })
      ? this.setData({ admin: true })
      : ''
  },
  getcity() {
    const token = wx.getStorageSync(`${getServer()}/logged`).data
    if (!token) return
    const location = wx.getStorageSync(`${getServer()}/logged`).data.location || ''
    const city = location.substring(location.lastIndexOf(' ') + 1)
    this.setData({
      city,
    })
  },
  onShareAppMessage() {
    return {
      path: $utils.getSharePath(),
    }
  },
  onShareTimeline() {
    return {
      title: '集梦116城市赛',
      query: 'from=timeline',
      imageUrl: 'https://houdong.ecoac.cn/images/share.png',
    }
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 判断是否滚动到了导航 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#header').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] ? res[0].bottom < 1 + this.data.navigationHeight : true,
      })
    })
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      navigationHeight: GlobalData.navigationHeight,
      [`item[4].name`]: GlobalData.access.video ? '短视频' : '图库',
    })
  },
  async fetchCategiries() {
    const categories = await feedApi.categiries()

    const navData = [
      { id: 1, name: '集梦月榜单' },
      { id: 2, name: '集梦日榜单' },
    ]
    this.setData({ categories, navData })
  },
  async updateCurrentTable(index: any) {
    if (!isLogin()) {
      await checkAuth()
    }
    this.getcity()
    const {
      data: {
        navData,
        query: { },
      },
    } = this
    this.setData(
      {
        currentIndex: parseInt(index),
        category: navData[parseInt(index)].id,
        method: index < 2 ? 'normal' : 'hot',
        query: {
          ...this.data.query,
          // 设置分类
          category: navData[parseInt(index)].id,
        },
      },
      async () => {
        const loaded = wx.getStorageSync(`loaded_${index}`)
        // 是否加载过，没有加载过则执行首次加载
        if (
          loaded !== true ||
          (loaded === true && (this.data.activitylist[index] || []).length === 0)
        ) {
          // const list = await this.fetchMatchList()
          const activitylist = await this.fetchMatchList()
          this.setData({
            activitylist: activitylist.data,
          })
        }
      },
    )
  },
  async changeCurrent(e: any) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    this.updateCurrentTable(index)
  },
  async onPullDownRefresh() {
    this.emitBoot()
    if (this.data.categories.length === 0) {
      await this.fetchCategiries()
    }
    this.getList()
    this.getMatchList()
    wx.stopPullDownRefresh()
  },
  /** 刷新设备信息 */
  emitBoot() {
    if (this.data.emit) return
    getApp().initDeviceInfo()
    $event.emit('boot')
  },
  async onReachBottom() {
    const {
      data: {
        currentIndex,
        query: { limit },
      },
    } = this
    const {
      data: {
        list: { [currentIndex]: feed },
      },
    } = this
    if (!feed.canLoaded) {
      wx.showToast({ title: '已没有更多', icon: 'none' })
      return
    }
    const list = await this.fetchList()
    this.setData({
      list: {
        ...this.data.list,
        [currentIndex]: {
          data: [...(this.data.list[currentIndex].data || []), ...list],
          canLoaded: list.length === limit || list.length > limit,
        },
      },
    })
    wx.hideLoading()
  },
  /** 获取数据(首次和刷新) */
  async getList() {
    const {
      data: {
        currentIndex,
        // method,
        query: { limit },
      },
    } = this
    this.setData({
      list: {
        ...this.data.list,
        [currentIndex]: { data: [], canLoaded: true },
      },
    })
    const list = await this.fetchList()
    this.setData({
      list: {
        ...this.data.list,
        [currentIndex]: { data: list, canLoaded: list.length === limit || list.length > limit },
      },
    })
  },
  /** 获取需要排除id的动态 */
  async fetchList(): Promise<DomoFeed[] | DomoTheme[]> {
    wx.showLoading({
      title: '加载中',
    })
    const {
      data: { method, query, currentIndex, loading },
    } = this
    if (loading) return []
    // 全部 table
    // const isAllTab = currentIndex === 0
    // 是否满足热门规则
    const isHotRule = method === 'hot'
    // 是否是点评
    // const isCommentDynamic = currentIndex === navData.length - 1
    // 热门动态请求需要排除的已看过的内容
    const excludes = isHotRule
      ? wx.getStorageSync(`${getServer()}/cacheFeeds_${currentIndex}`).data || []
      : []
    this.setData({
      loading: true,
    })
    const imageWidth = 300
    try {
      const list = isHotRule
        ? await feedApi.getRandomFeeds({
          exclude_feeds: Array.from(new Set(excludes)) as number[],
          category: query.category,
          limit: query.limit,
          repostable_type: 'mall_commodities,knowledge',
          image_rule: 'image/resize,s_' + imageWidth,
        })
        : false
          ? await feedApi.getFeeds({
            after: this.data.list[currentIndex]
              ? this.data.list[currentIndex].data.length > 1
                ? this.data.list[currentIndex].data[this.data.list[currentIndex].data.length - 1].id
                : 0
              : 0,
            limit: query.limit,
            type: 'new',
            image_rule: 'image/resize,s_' + imageWidth,
          })
          : await feedApi.getFeeds({
            offset: this.data.list[currentIndex]
              ? this.data.list[currentIndex].data.length > 1
                ? this.data.list[currentIndex].data.length
                : 0
              : 0,
            limit: query.limit,
            type: 'newFollow',
            image_rule: 'image/resize,s_' + imageWidth,
          })
      wx.setStorageSync(`loaded_${currentIndex}`, true)
      this.setData({ loading: false })
      wx.hideLoading()
      // 如果没有新动态了, 就清除排除的id数组, 重新来过
      if (list.length === 0) {
        // 避免陷入无限请求
        if (!excludes.length) return []
        if (isHotRule) $storage.remove(`cacheFeeds_${currentIndex}`)
        return this.fetchList()
      }
      excludes.push(...list.map((item: any) => item.id))
      if (isHotRule) $storage.set(`cacheFeeds_${currentIndex}`, excludes)
      return list
    } catch (error) {
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'none',
        duration: 1000,
      })
      wx.hideLoading()
    }
    return []
  },
  /** 获取数据(首次和刷新) */
  async getMatchList() {
    const list = await this.fetchMatchList()
    this.setData({
      activitylist: list.data,
    })
    console.log(this.data.activitylist)
  },
  async fetchMatchList(): Promise<DomoMatchListsData> {
    wx.showLoading({
      title: '加载中',
    })
    const {
      data: { query },
    } = this
    this.setData({
      loading: true,
    })
    const matchlist = await feedApi.getMatchList({
      limit: query.limit,
      category_id: this.data.currentIndex,
      page: 1,
      audited: 1,
      admin_sort: 'down',
    })
    for (const index in matchlist.data) {
      matchlist.data[index].date = matchlist.data[index].date.slice(0, 10)
      if (
        matchlist.data[index].expired_date &&
        matchlist.data[index].expired_date < this.getCurrentDate()
      ) {
        matchlist.data[index].is_expired = 1
      } else {
        matchlist.data[index].is_expired = 0
      }
    }
    wx.setStorageSync(`loaded_match_1`, true)
    this.setData({ loading: false })
    wx.hideLoading()
    return matchlist
  },
  getCurrentDate() {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    // console.log(`${year}-${month}-${day}`)
    return `${year}-${month}-${day}`
  },
  async fetchTopics(list: DomoFeed[]) {
    const ids = list.filter((feed) => feed.topics.length).map((feed) => feed.topics[0]!.id)
    const topics = await topicApi.getTopics([...new Set(ids)].join(','))
    return topics
  },
  onDownload() {
    $event.emit('download')
  },
  toDetail(e: WechatMiniprogram.BaseEvent) {
    // console.log(e)
    // const id = e.currentTarget.dataset.id as number
    // wx.navigateTo({
    //   url: `/pages/match/detail/detail?id=${id}&from=matchdetail`,
    // })
  },
  toBuy(e: WechatMiniprogram.BaseEvent) {
    console.log(e.currentTarget.dataset.id)
    const id = e.currentTarget.dataset.id
    if (!isLogin()) {
      console.log('not login list')
      checkAuth()
    } else {
      wx.navigateTo({
        url: `/pages/match/baoming/baoming?event_id=${id}`,
      })
    }
  },
  themeDetail(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id as number
    wx.navigateTo({
      url: `/pages/theme/detail/detail?id=${id}`,
    })
  },
  async jump(e: WechatMiniprogram.BaseEvent) {
    const item = e.currentTarget.dataset.item
    if (!isLogin()) {
      await checkAuth()
    }
    if (!item.show_link) {
      wx.showToast({
        title: '功能开发中',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (item.type == 1) {
      wx.navigateTo({
        url: item.show_link,
      })
    } else if (item.type == 2) {
      wx.setStorageSync('pathUrl', item.show_link)
      wx.navigateTo({
        url: '/mine/customerService/customerService',
      })
    } else {
      wx.navigateToMiniProgram({
        appId: item.show_link,
        // path: 'pages/page2/page2?id=123',
        success(res) {
          console.info(res)
          // 打开成功
        },
      })
    }
  },
})
